import Vue from 'vue'
import Router from 'vue-router'
import Routes from './routes'
import { getToken,getUserInfo,getLock } from '../utils/permission.js'

Vue.use(Router)

const originalPush = Router.prototype.push
// 重写了原型上的push方法，统一的处理了错误信息
Router.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

// 项目名称（请在使用时仅修改值内容）
Vue.prototype.projectName = 'Vue Element Simple';

const router = new Router({
	mode: "history",
	routes: [
		{
			path: '/',
			redirect: '/index',
			component: () => import('@/layouts/Container'),
			children: [
				...Routes
			]
		},
		{
			path: '/lock',
			name: 'Lock',
			component: () => import('@/views/lock'),
			meta: {
				title: '锁屏界面',
				showFooter: false
			}
		},
		{
			path: '/login',
			name: 'Login',
			component: () => import('@/views/login/index'),
			meta: {
				title: '登录',
				showFooter: true
			}
		}
	]
})

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 导航守卫（前置）
router.beforeEach((to, from, next) => {
	// 关闭右侧圈圈
	NProgress.configure({ showSpinner: false })
	// 开始进度条
	NProgress.start();
	// 设置标题
	document.title = `${to.meta.title} - ${Vue.prototype.projectName}`;
	if (to.name !== "Login" && to.name !== "Forget" && to.name !== "Register") {
		if (to.matched.length === 0) {
			next({path:'/404'})
		} else {
			if (getToken()) {
				// 需要锁屏操作
				if (getLock() && to.name !== "Lock") {
					next({path:'/lock'})
				}
				// 需要权限访问
				if (to.meta.requiresAuth) {
					let userInfo = JSON.parse(getUserInfo());
					if (to.meta.roles.indexOf(userInfo.role) === -1) {
						next({path:'/401'})
					}
				}
				next()
			} else {
				next({path:'/login'})
			}
		}
	} else {
		next()
	}
})

// 导航守卫（后置）
router.afterEach(transition => {
	// 结束进度条
	NProgress.done()
})

export default router
